package main

import (
	"fmt"
	"log"
	"os/exec"
	"strings"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
)

// RemoteControl 遥控器按键定义
type RemoteControl struct{}

// NewRemoteControl 创建新的遥控器实例
func NewRemoteControl() *RemoteControl {
	return &RemoteControl{}
}

// 获取缩放比例
func getScaleFactor() float32 {
	// 检测系统DPI缩放比例
	// 在Linux上，通常可以通过环境变量或系统设置获取
	// 这里我们使用一个简单的检测方法
	scale := float32(1.0)

	// 检查环境变量
	if scaleEnv, err := exec.Command("gsettings", "get", "org.gnome.desktop.interface", "scaling-factor").Output(); err == nil {
		if strings.Contains(string(scaleEnv), "2") {
			scale = 2.0
		}
	}

	// 如果无法检测，默认使用2.0（适合200%缩放）
	return scale
}

// executeADBCommand 执行adb命令
func (rc *RemoteControl) executeADBCommand(args ...string) error {
	// 构建完整的adb命令
	cmd := exec.Command("adb", args...)

	log.Printf("执行命令: adb %s", strings.Join(args, " "))

	// 执行命令
	return cmd.Run()
}

// SendKey 发送按键事件
func (rc *RemoteControl) SendKey(keyCode int, keyName string) error {
	log.Printf("📱 发送按键: %s (代码: %d)", keyName, keyCode)
	return rc.executeADBCommand("shell", "input", "keyevent", fmt.Sprintf("%d", keyCode))
}

// SendText 发送文本
func (rc *RemoteControl) SendText(text string) error {
	log.Printf("📝 发送文本: %s", text)
	return rc.executeADBCommand("shell", "input", "text", text)
}

// Tap 点击屏幕坐标
func (rc *RemoteControl) Tap(x, y int) error {
	log.Printf("👆 点击坐标: (%d, %d)", x, y)
	return rc.executeADBCommand("shell", "input", "tap", fmt.Sprintf("%d", x), fmt.Sprintf("%d", y))
}

// Swipe 滑动屏幕
func (rc *RemoteControl) Swipe(x1, y1, x2, y2 int, duration int) error {
	log.Printf("👆 滑动: (%d,%d) -> (%d,%d), 时长: %dms", x1, y1, x2, y2, duration)
	return rc.executeADBCommand("shell", "input", "swipe",
		fmt.Sprintf("%d", x1), fmt.Sprintf("%d", y1),
		fmt.Sprintf("%d", x2), fmt.Sprintf("%d", y2),
		fmt.Sprintf("%d", duration))
}

// 遥控器按键代码定义
const (
	// 方向键
	KEY_UP    = 19
	KEY_DOWN  = 20
	KEY_LEFT  = 21
	KEY_RIGHT = 22

	// 确认键
	KEY_ENTER       = 66
	KEY_DPAD_CENTER = 23

	// 返回键
	KEY_BACK = 4

	// 菜单键
	KEY_MENU = 82

	// 主页键
	KEY_HOME = 3

	// 音量键
	KEY_VOLUME_UP   = 24
	KEY_VOLUME_DOWN = 25
	KEY_VOLUME_MUTE = 164

	// 数字键
	KEY_0 = 7
	KEY_1 = 8
	KEY_2 = 9
	KEY_3 = 10
	KEY_4 = 11
	KEY_5 = 12
	KEY_6 = 13
	KEY_7 = 14
	KEY_8 = 15
	KEY_9 = 16

	// 功能键
	KEY_POWER        = 26
	KEY_PLAY_PAUSE   = 85
	KEY_STOP         = 86
	KEY_NEXT         = 87
	KEY_PREVIOUS     = 88
	KEY_FAST_FORWARD = 90
	KEY_REWIND       = 89
)

// 创建按钮并绑定事件
func createButton(rc *RemoteControl, text string, keyCode int, size fyne.Size) *widget.Button {
	btn := widget.NewButton(text, func() {
		if err := rc.SendKey(keyCode, text); err != nil {
			log.Printf("❌ 发送按键失败: %v", err)
		}
	})
	btn.Resize(size)
	return btn
}

// 创建数字按钮
func createNumberButton(rc *RemoteControl, num int, keyCode int) *widget.Button {
	scale := getScaleFactor()
	baseSize := float32(50)
	size := baseSize * scale
	return createButton(rc, fmt.Sprintf("%d", num), keyCode, fyne.NewSize(size, size))
}

// 创建方向键按钮
func createDirectionButton(rc *RemoteControl, text string, keyCode int) *widget.Button {
	scale := getScaleFactor()
	baseSize := float32(60)
	size := baseSize * scale
	return createButton(rc, text, keyCode, fyne.NewSize(size, size))
}

// 创建功能按钮
func createFunctionButton(rc *RemoteControl, text string, keyCode int) *widget.Button {
	scale := getScaleFactor()
	baseWidth := float32(80)
	baseHeight := float32(50)
	width := baseWidth * scale
	height := baseHeight * scale
	return createButton(rc, text, keyCode, fyne.NewSize(width, height))
}

func main() {
	// 创建应用
	myApp := app.New()
	myApp.SetIcon(nil) // 可以设置应用图标

	// 创建主窗口
	window := myApp.NewWindow("🎮 BabyTap TV 遥控器")
	scale := getScaleFactor()
	baseWidth := float32(600)
	baseHeight := float32(800)
	width := baseWidth * scale
	height := baseHeight * scale
	window.Resize(fyne.NewSize(width, height))
	window.CenterOnScreen()

	// 创建遥控器实例
	rc := NewRemoteControl()

	// 检查adb是否可用
	if err := exec.Command("adb", "version").Run(); err != nil {
		log.Println("❌ 错误: adb命令不可用")
		log.Println("💡 请确保Android SDK已安装且adb在PATH中")
		return
	}

	// 检查设备连接状态
	cmd := exec.Command("adb", "devices")
	output, err := cmd.Output()
	if err != nil {
		log.Printf("❌ 检查设备失败: %v", err)
		return
	}

	deviceList := string(output)
	if !strings.Contains(deviceList, "device") {
		log.Println("❌ 未发现已连接的设备")
		log.Println("💡 请确保设备已连接并启用ADB调试")
		return
	}

	log.Println("✅ 设备连接正常")

	// 状态标签
	statusLabel := widget.NewLabel("📱 设备已连接")
	statusLabel.Alignment = fyne.TextAlignCenter

	// 方向键区域
	upBtn := createDirectionButton(rc, "⬆️", KEY_UP)
	downBtn := createDirectionButton(rc, "⬇️", KEY_DOWN)
	leftBtn := createDirectionButton(rc, "⬅️", KEY_LEFT)
	rightBtn := createDirectionButton(rc, "➡️", KEY_RIGHT)
	centerBtn := createDirectionButton(rc, "OK", KEY_DPAD_CENTER)

	directionContainer := container.NewGridWithColumns(3,
		widget.NewLabel(""), upBtn, widget.NewLabel(""),
		leftBtn, centerBtn, rightBtn,
		widget.NewLabel(""), downBtn, widget.NewLabel(""),
	)

	// 功能键区域
	homeBtn := createFunctionButton(rc, "🏠 HOME", KEY_HOME)
	backBtn := createFunctionButton(rc, "🔙 BACK", KEY_BACK)
	menuBtn := createFunctionButton(rc, "📋 MENU", KEY_MENU)

	functionContainer := container.NewHBox(homeBtn, backBtn, menuBtn)

	// 音量控制区域
	volUpBtn := createFunctionButton(rc, "🔊 +", KEY_VOLUME_UP)
	volDownBtn := createFunctionButton(rc, "🔉 -", KEY_VOLUME_DOWN)
	muteBtn := createFunctionButton(rc, "🔇 MUTE", KEY_VOLUME_MUTE)

	volumeContainer := container.NewHBox(volUpBtn, volDownBtn, muteBtn)

	// 播放控制区域
	playBtn := createFunctionButton(rc, "▶️ PLAY", KEY_PLAY_PAUSE)
	stopBtn := createFunctionButton(rc, "⏹️ STOP", KEY_STOP)
	nextBtn := createFunctionButton(rc, "⏭️ NEXT", KEY_NEXT)
	prevBtn := createFunctionButton(rc, "⏮️ PREV", KEY_PREVIOUS)

	playbackContainer := container.NewHBox(prevBtn, playBtn, stopBtn, nextBtn)

	// 数字键区域
	numberButtons := make([]fyne.CanvasObject, 10)
	for i := 0; i < 10; i++ {
		var keyCode int
		switch i {
		case 0:
			keyCode = KEY_0
		case 1:
			keyCode = KEY_1
		case 2:
			keyCode = KEY_2
		case 3:
			keyCode = KEY_3
		case 4:
			keyCode = KEY_4
		case 5:
			keyCode = KEY_5
		case 6:
			keyCode = KEY_6
		case 7:
			keyCode = KEY_7
		case 8:
			keyCode = KEY_8
		case 9:
			keyCode = KEY_9
		}
		numberButtons[i] = createNumberButton(rc, i, keyCode)
	}

	numberContainer := container.NewGridWithColumns(3,
		numberButtons[1], numberButtons[2], numberButtons[3],
		numberButtons[4], numberButtons[5], numberButtons[6],
		numberButtons[7], numberButtons[8], numberButtons[9],
		widget.NewLabel(""), numberButtons[0], widget.NewLabel(""),
	)

	// 特殊功能区域
	powerBtn := createFunctionButton(rc, "🔌 POWER", KEY_POWER)
	ffBtn := createFunctionButton(rc, "⏩ FF", KEY_FAST_FORWARD)
	rewBtn := createFunctionButton(rc, "⏪ REW", KEY_REWIND)

	specialContainer := container.NewHBox(powerBtn, ffBtn, rewBtn)

	// 触摸操作区域
	tapXEntry := widget.NewEntry()
	tapXEntry.SetPlaceHolder("X坐标")
	tapYEntry := widget.NewEntry()
	tapYEntry.SetPlaceHolder("Y坐标")

	tapBtn := widget.NewButton("👆 点击", func() {
		// 这里可以添加坐标解析和点击逻辑
		log.Println("点击功能待实现")
	})

	tapContainer := container.NewHBox(
		widget.NewLabel("坐标:"),
		tapXEntry,
		tapYEntry,
		tapBtn,
	)

	// 文本输入区域
	textEntry := widget.NewEntry()
	textEntry.SetPlaceHolder("输入文本...")
	textBtn := widget.NewButton("📝 发送", func() {
		text := textEntry.Text
		if text != "" {
			if err := rc.SendText(text); err != nil {
				log.Printf("❌ 发送文本失败: %v", err)
			}
			textEntry.SetText("")
		}
	})

	textContainer := container.NewHBox(textEntry, textBtn)

	// 日志区域
	logText := widget.NewMultiLineEntry()
	logText.SetPlaceHolder("操作日志...")
	logText.Disable()

	// 主布局
	content := container.NewVBox(
		statusLabel,
		widget.NewSeparator(),
		widget.NewLabel("🎯 方向键"),
		directionContainer,
		widget.NewSeparator(),
		widget.NewLabel("🔧 功能键"),
		functionContainer,
		widget.NewSeparator(),
		widget.NewLabel("🔊 音量控制"),
		volumeContainer,
		widget.NewSeparator(),
		widget.NewLabel("🎵 播放控制"),
		playbackContainer,
		widget.NewSeparator(),
		widget.NewLabel("🔢 数字键"),
		numberContainer,
		widget.NewSeparator(),
		widget.NewLabel("⚡ 特殊功能"),
		specialContainer,
		widget.NewSeparator(),
		widget.NewLabel("👆 触摸操作"),
		tapContainer,
		widget.NewSeparator(),
		widget.NewLabel("📝 文本输入"),
		textContainer,
		widget.NewSeparator(),
		widget.NewLabel("📋 操作日志"),
		logText,
	)

	// 设置主内容
	window.SetContent(container.NewVScroll(content))

	// 运行应用
	window.ShowAndRun()
}
